package com.example.city_home_app.Activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.example.city_home_app.Bean.Down_Post;
import com.example.city_home_app.Bean.Down_Universe;
import com.example.city_home_app.Bean.Down__Image;
import com.example.city_home_app.Model.ApiModel;
import com.example.city_home_app.R;
import com.example.city_home_app.RecyclerViewAdapter.Adapter_PostAdd;
import com.example.city_home_app.RetrofitListener;
import com.example.city_home_app.UI.UIUtils;
import com.google.gson.Gson;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PostAddActivity extends BaseActivity {
    @BindView(R.id.tv_postadd_addpic)
    TextView tvPostaddAddpic;
    @BindView(R.id.toolbar_post_addpost)
    Toolbar toolbarCommunityAllcommunity;
    @BindView(R.id.et_postadd_title)
    EditText etPostaddTitle;
    @BindView(R.id.et_postadd_content)
    EditText etPostaddContent;
    @BindView(R.id.rec_postaddimg)
    RecyclerView recPostaddimg;

    public static PostAddActivity instance;
    @BindView(R.id.tv_postadd_submit)
    TextView tvPostaddSubmit;

    private List<Uri> list;
    private int currentimg = 0, deleteposition,oncreatetype,postid,communityid;
    private String content = "";
    private Adapter_PostAdd adapter_postadd;
    private List<String> uploadimgurls = new ArrayList<>();
    private List<Down__Image> downloadimgurls = new ArrayList<>();

    private RetrofitListener<List<Down__Image>> imgretrofitListener = new RetrofitListener<List<Down__Image>>() {
        @Override
        public void onResponse(List<Down__Image> listener) {
            content = etPostaddContent.getText().toString();
            for (int i = 0; i < listener.size(); i++) {
                downloadimgurls.add(listener.get(i));
                content += "<img src=\"" + listener.get(i).getImg() + "\\\"/>";
            }
            uploadimgurls.clear();
            etPostaddContent.setText(content);
            if (currentimg != 0) {
                recPostaddimg.setVisibility(View.VISIBLE);
                adapter_postadd.setList(downloadimgurls);
                adapter_postadd.notifyDataSetChanged();
            } else {
                recPostaddimg.setVisibility(View.GONE);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<Down_Post> postRetrofitListener = new RetrofitListener<Down_Post>() {
        @Override
        public void onResponse(Down_Post listener) {
            etPostaddTitle.setText(listener.getPost_title());
            etPostaddContent.setText(listener.getPost_content());
            List<String> list = cutStringByImgTag(listener.getPost_content());
            for (String s : list) {
                if (s.startsWith("<img src=")) {
                    currentimg++;
                    Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                    Matcher m_src = p_src.matcher(s);
                    if (m_src.find()) {
                        String a = m_src.group(3);
                        String i = a.replace("\\","");
                        Down__Image bean = new Down__Image();
                        bean.setImg(i);
                        downloadimgurls.add(bean);
                    }
                }
            }
            adapter_postadd.setList(downloadimgurls);
            adapter_postadd.notifyDataSetChanged();
        }

        @Override
        public void onFail(String msg) {

        }
    };

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_postadd;
    }

    @Override
    protected void initViews() {
        super.initViews();
        Window window = PostAddActivity.this.getWindow();
        //如果系统5.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0xff49afcd);
        }

        instance = this;
        ButterKnife.bind(this);
        recPostaddimg = (RecyclerView) findViewById(R.id.rec_postaddimg);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recPostaddimg.setLayoutManager(layoutManager);
        adapter_postadd = new Adapter_PostAdd(this,1);
        recPostaddimg.setAdapter(adapter_postadd);
        recPostaddimg.setItemAnimator(new DefaultItemAnimator());

        showToast();
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        oncreatetype = intent.getIntExtra("type",0);
        if(oncreatetype==1){
            toolbarCommunityAllcommunity.setTitle("编辑帖子");
            tvPostaddSubmit.setText("保存");
            postid = intent.getIntExtra("id",0);
            ApiModel model = new ApiModel();
            model.getpost(postid,postRetrofitListener);
        }else{
            communityid = intent.getIntExtra("id",0);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 100 && resultCode == RESULT_OK) {
                    list = Matisse.obtainResult(data);
                    for (Uri uri : list) {
                        String path = UIUtils.getFilePathFromUri(this, uri);
                        uploadimgurls.add(path);
                        currentimg++;
                        /*String contentpath = "<img src=\""+path+"\\\"/>";
                        content+=contentpath;
                        etPostaddContent.setText(content);*/
                    }
                    ApiModel model = new ApiModel();
                    model.uppostimgs((ArrayList) uploadimgurls, imgretrofitListener);
                    //List<String> list = cutStringByImgTag(content);
                    /*for(String s :list){
                        content = content.replace(s,"这里是一张图片");
                        Log.d("img", s);
                    }
                    etPostaddContent.setText(content);*/
                }
            }
        }
    }

    public static List<String> cutStringByImgTag(String targetStr) {
        List<String> splitTextList = new ArrayList<String>();
        Pattern pattern = Pattern.compile("<img.*?src=\\\"(.*?)\\\".*?>");
        Matcher matcher = pattern.matcher(targetStr);
        int lastIndex = 0;
        while (matcher.find()) {
            if (matcher.start() > lastIndex) {
                splitTextList.add(targetStr.substring(lastIndex, matcher.start()));
            }
            splitTextList.add(targetStr.substring(matcher.start(), matcher.end()));
            lastIndex = matcher.end();
        }
        if (lastIndex != targetStr.length()) {
            splitTextList.add(targetStr.substring(lastIndex, targetStr.length()));
        }
        return splitTextList;
    }

    private RetrofitListener<Down_Universe> dellistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                content = etPostaddContent.getText().toString();
                content = content.replace("<img src=\"" + downloadimgurls.get(deleteposition).getImg() + "\\\"/>", "");
                etPostaddContent.setText(content);
                downloadimgurls.remove(deleteposition);
                adapter_postadd.setList(downloadimgurls);
                adapter_postadd.notifyDataSetChanged();
                currentimg--;
                UIUtils.showToast(PostAddActivity.this, "删除成功", UIUtils.LENGTH_SHORT);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    public void deleteimg(int position) {
        deleteposition = position;
        ApiModel model = new ApiModel();
        List<Down__Image> list = new ArrayList<>();
        Down__Image bean = downloadimgurls.get(position);
        list.add(bean);
        Gson gson = new Gson();
        String json = gson.toJson(list);
        model.delpostimgs(json, dellistener);
    }

    private RetrofitListener<Down_Universe> uplistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if(listener.getMessage().equals("success")){
                UIUtils.showToast(PostAddActivity.this,"提交成功",UIUtils.LENGTH_SHORT);
                finish();
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<Down_Universe> updatelistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if(listener.getMessage().equals("success")){
                UIUtils.showToast(PostAddActivity.this,"保存成功",UIUtils.LENGTH_SHORT);
                finish();
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };



    @OnClick({R.id.tv_postadd_submit, R.id.tv_postadd_addpic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_postadd_submit:
                if(!etPostaddContent.getText().toString().equals("")&&!etPostaddTitle.getText().toString().equals("")){
                    ApiModel model = new ApiModel();
                    if(oncreatetype==0) {
                        model.uppost(BaseActivity.getUserinfo().getCityid(), communityid, etPostaddTitle.getText().toString(), etPostaddContent.getText().toString(), BaseActivity.getUserinfo().getUserid(), uplistener);
                    }else{
                        model.updatepost(postid,etPostaddTitle.getText().toString(),etPostaddContent.getText().toString(),updatelistener);
                    }
                }else{
                    UIUtils.showToast(this,"内容不能为空",UIUtils.LENGTH_SHORT);
                }
                break;
            case R.id.tv_postadd_addpic:
                if (currentimg != 3) {
                    Matisse.from(this)
                            .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))
                            .countable(true)
                            .maxSelectable(3 - currentimg)
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .thumbnailScale(0.85f)
                            .theme(R.style.Matisse_Zhihu)
                            .imageEngine(new PicassoEngine())
                            .capture(false)
                            .forResult(100);
                } else {
                    UIUtils.showToast(this, "最多上传三张图片", UIUtils.LENGTH_SHORT);
                }
                break;
        }
    }

    private void showToast() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        toolbarCommunityAllcommunity = (Toolbar) findViewById(R.id.toolbar_post_addpost);

        setSupportActionBar(toolbarCommunityAllcommunity);

        toolbarCommunityAllcommunity.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setSupportActionBar(toolbarCommunityAllcommunity);
    }
}
